#include <stdio.h>
#include <stdlib.h>

#include "fifo.h"

#define TAILLE_MAX 10000

struct fifo
{
   int size;
   int n_elts;
   int iw;
   int ir;
   unsigned char elts[TAILLE_MAX];
};

struct fifo * fifo_empty ()
{
	struct fifo * f = (struct fifo *) malloc (sizeof(struct fifo));
	f->n_elts=0;
	f->iw = 0;
	f->ir = 0;
  f->size=TAILLE_MAX;
  return f;
}

int fifo_is_empty (struct fifo * f)
{
  return (f->n_elts == 0);
}


int fifo_top (struct fifo * f)
{
  if (!fifo_is_empty(f))
  {
    unsigned char a = f->elts[f->ir];
		return (a);
  }
  else
  {
    fifo_errno = FIFO_EMPTY;
    return(-1);
  }
}


int fifo_push ( struct fifo * f, unsigned char e)
{
  if(f->n_elts <= f->size)
  {
    f->elts[f->iw] = e;
    f->iw = (f->iw +1) % (f->size) ;
    f->n_elts ++ ;
    return 0;
  }
  else
  {
    fifo_errno = FIFO_FULL;
    return 1;
  }
}

int fifo_pop (struct fifo * f)
{
  if (!fifo_is_empty (f))
  {
    f->ir = (f->ir +1) % (f->size) ;
    f-> n_elts --;
    return 0;
  }
  else
  {
  	fifo_errno = FIFO_EMPTY;
  	return 1;
  }
}

int fifo_free (struct fifo * f)
{
	free(f);
	return 0;
}
